
#include "pan_rf.h"
#include "oled.h"
#include "display.h"
#include "key_handle.h"
#include "utilities.h"

uint32_t tx_mode = 0;
uint32_t tx_power = 22;
uint32_t freq_mode = 0;
uint32_t tx_pkt_max_num = 1;
uint32_t tx_pkt_cnt = 0;
uint32_t rx_pkt_cnt = 0;
uint8_t tx_buf[256];
uint32_t tx_len = 10;
uint32_t tx_time;
uint32_t tx_ing = 0;
uint32_t keys_pressed = 0;
uint32_t key_second_pressed = 0;
uint32_t sys_tick = 0;
uint8_t key_set_test_mode1_flag = 0;
uint8_t tx_carrywave_flag = false;
uint32_t g_RxCount = 0;

extern uint32_t g_UserTxMode;
extern uint32_t freq_list[FREQ_LIST_NUM];
extern RfRxPkt_t g_RfRxPkt;

bool g_RFTxOta = false;             /* 是否有单包数据正在空中发送 */

typedef struct
{
    en_port_t    port;
    en_pin_t     pin;
} BSP_KeyIn_Config;

static const BSP_KeyIn_Config BSP_KEYIN_PORT_PIN[BSP_KEY_ROW_NUM] = 
{
    {BSP_KEY1_PORT, BSP_KEY1_PIN},
    {BSP_KEY2_PORT, BSP_KEY2_PIN},
    {BSP_KEY3_PORT, BSP_KEY3_PIN},
    {BSP_KEY4_PORT, BSP_KEY4_PIN},
    {BSP_KEY5_PORT, BSP_KEY5_PIN},
    {BSP_KEY6_PORT, BSP_KEY6_PIN},
};

typedef struct
{
    en_port_t port;
    en_pin_t pin;
    uint32_t first_state;
    uint32_t second_state;
    uint32_t last_tick;
    void (*func)(void);
    void (*func_second)(void);
} key_info_t;

key_info_t key_list[6] =
{
    [0] = {
        .port = BSP_KEY2_PORT,
        .pin = BSP_KEY2_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = key_clear_cnt,
        .func_second = key_set_test_mode1,
    },
    [1] = {
        .port = BSP_KEY3_PORT,
        .pin = BSP_KEY3_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = key_set_start_tx_routine,
        .func_second = key_set_fq_routine,
    },
    [2] = {
        .port = BSP_KEY4_PORT,
        .pin = BSP_KEY4_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = key_set_mode_routine,
        .func_second = key_set_cr_routine,
    },
    [3] = {
        .port = BSP_KEY5_PORT,
        .pin = BSP_KEY5_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = key_set_sf_routine,
        .func_second = key_set_pl_routine,
    },
    [4] = {
        .port = BSP_KEY6_PORT,
        .pin = BSP_KEY6_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = key_set_bw_routine,
        .func_second = key_set_power_routine,
    },

    [5] = {
        .port = BSP_KEY1_PORT,
        .pin = BSP_KEY1_PIN,
        .first_state = 0,
        .second_state = 0,
        .last_tick = 0,
        .func = NULL,
    },
};

void key_set_sf_routine(void)
{
    uint32_t para;

    RF_SetRfState(RF_STATE_STB3);
    para = RF_GetSF();
    para++;
    if (para > 12)
    {
        para = 5;
    }
    dis_set_sf(para);
    oled_refresh();
    RF_SetSF(para);
    if (g_UserTxMode)
    {
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_set_bw_routine(void)
{
    uint32_t para;

    RF_SetRfState(RF_STATE_STB3);
    para = RF_GetBandWidth();
    para++;
    if (para > 9)
    {
        para = 6;
    }
    dis_set_bw(para);
    oled_refresh();
    RF_SetBW(para);
    if (g_UserTxMode)
    {
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_set_pl_routine(void)
{
    tx_len += 10;
    if (tx_len > 240)
    {
        tx_len = 10;
    }
    dis_set_pl(tx_len);

    /* 每次切换数据长度时，重新填充数据及计算CRC校验值 */
    for(int i = 0; i < tx_len; i++)
    {
        tx_buf[i] = i;
    }

    uint16_t crc16 = crc16_ccitt(tx_buf, tx_len - 2); /* 计算CRC校验值 */
    tx_buf[tx_len - 2] = (uint8_t)(crc16 >> 8);       /* CRC高字节 */
    tx_buf[tx_len - 1] = crc16 & 0xFF;                /* CRC低字节 */
    
    print_hex(tx_buf, tx_len); /* 打印发送数据 */

    oled_refresh();
}

void key_set_mode_routine(void)
{
    tx_mode++;
    if (tx_mode > 3)
    {
        tx_mode = 0;
    }
    dis_set_mode(tx_mode);
    oled_refresh();

    if (tx_carrywave_flag == true)
    {
        RF_StopTxContinuousWave();
        RF_ClrIRQFlag(RF_IRQ_TX_DONE);
        tx_carrywave_flag = false;
    }

    if (tx_mode == 0)
    {
        tx_pkt_max_num = 1;
    }
    else if (tx_mode == 1)
    {
        tx_pkt_max_num = 100;
    }
    else if (tx_mode == 2)
    {
        tx_pkt_max_num = 9999;
    }
    else
    {
        if (g_UserTxMode)
        {
            // 发送载波前须设置好频率和功率
            RF_SetFreq(freq_list[freq_mode] * 100000);
            RF_SetTxPower(tx_power);
            RF_StartTxContinuousWave();
            tx_carrywave_flag = true;
        }
    }
}

void key_set_power_routine(void)
{
    uint32_t para;

    RF_SetRfState(RF_STATE_STB3);
    para = RF_GetTxPower();

    if (para >= 22)
    {
        para = 1;
    }
    else
    {
        para++;
    }
    tx_power = para;
    RF_SetTxPower(para);
    SysTick_Delay(1);
    para = RF_GetTxPower();

    dis_set_txpower(para);
    oled_refresh();
    if (g_UserTxMode)
    {
        if (tx_carrywave_flag)
        {
            RF_StopTxContinuousWave();
            // 发送载波前须设置好频率和功率
            RF_SetFreq(freq_list[freq_mode] * 100000);
            RF_SetTxPower(tx_power);
            RF_StartTxContinuousWave();
        }
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_set_cr_routine(void)
{
    uint32_t para;

    RF_SetRfState(RF_STATE_STB3);
    para = RF_GetCR();
    para++;
    if (para > 4)
    {
        para = 1;
    }
    dis_set_cr(para);
    oled_refresh();
    RF_SetCR(para);
    if (g_UserTxMode)
    {
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_set_start_tx_routine(void)
{
    if (g_UserTxMode)
    {
        
        tx_ing++;
        tx_ing %= 2;
        
        if(g_RFTxOta)
        {
            printf("Tx packet is ongoing.\r\n");
            return; /* 如果有单包数据正在空中发送，则不处理发送 */
        }
        
        if (tx_ing || (tx_pkt_max_num == 1))
        {
            if (tx_pkt_max_num != 1)
            {
                tx_pkt_cnt = 0;
            }
            // else
            // {
            //     g_RFTxOta = true;  /* 标记有单包数据正在空中发送 */
            // }
            g_RFTxOta = true;  /* 标记有单包数据正在空中发送 */
            RF_TxSinglePkt(tx_buf, tx_len);
        }
        // if (tx_ing)
        // {
        //     if (tx_pkt_max_num != 1)
        //     {
        //         tx_pkt_cnt = 0;
        //     }
        //     // else
        //     // {
        //     //     g_RFTxOta = true;  /* 标记有单包数据正在空中发送 */
        //     // }
        //     RF_TxSinglePkt(tx_buf, tx_len);
        // }
        // else if(!tx_ing && tx_pkt_max_num == 1)
        // {
        //     g_RFTxOta = true;  /* 标记有单包数据正在空中发送 */
        // }
    }
}

void key_set_fq_routine(void)
{
    uint32_t para;

    freq_mode++;
    if (freq_mode > FREQ_LIST_NUM - 1)
    {
        freq_mode = 0;
    }

    if (freq_mode == 0)
    {
        para = freq_list[freq_mode] * 100000;
    }
    else if (freq_mode == 1)
    {
        para = freq_list[freq_mode] * 100000;
    }
    else
    {
        para = freq_list[freq_mode] * 100000;
    }

    RF_SetRfState(RF_STATE_STB3);
    RF_SetFreq(para);

    para = RF_GetFreq();

    dis_set_fq((para / 100000));

    oled_refresh();

    if (g_UserTxMode)
    {
        if (tx_carrywave_flag)
        {
            RF_StopTxContinuousWave();
            // 发送载波前须设置好频率和功率
            RF_SetFreq(freq_list[freq_mode] * 100000);
            RF_SetTxPower(tx_power);
            RF_StartTxContinuousWave();
        }
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_clear_cnt(void)
{
    tx_pkt_cnt = 0;
    rx_pkt_cnt = 0;
    dis_set_cnt(0);
    oled_refresh();
}

void key_set_test_mode1(void)
{
    RF_SetRfState(RF_STATE_STB3);
    key_set_test_mode1_flag++;
    if (key_set_test_mode1_flag > 2)
    {
        key_set_test_mode1_flag = 0;
    }

    if (key_set_test_mode1_flag == 1)
    {
        RF_SetChipMode(CHIPMODE_MODE1); /* 设置芯片模式为MODE1 */
        RF_SetCRC(RF_CRC_OFF);          /* 关闭CRC校验 */
    }
    else
    {
        RF_SetChipMode(CHIPMODE_MODE0); /* 设置芯片模式为MODE0 */
        RF_SetCRC(RF_CRC_ON);           /* 开启CRC校验 */
    }

    dis_set_test_mode1(key_set_test_mode1_flag);
    oled_refresh();

    if (g_UserTxMode)
    {
        
    }
    else
    {
        RF_TurnonRxAnt();
        RF_SetRfState(RF_STATE_RX);
    }
}

void key_scan(void)
{
    uint8_t i;
    uint8_t pin_state;
    uint8_t pin_state_second;
    sys_tick = SysTick_GetTick();

    if (sys_tick % 50)
    {
        return;
    }

    for (i = 0; i < 5; i++)
    {
        pin_state = PORT_GetBit(key_list[i].port, key_list[i].pin);

        if ((pin_state == RESET) && (key_list[i].first_state == SET) && (key_list[i].second_state == RESET))
        {
            keys_pressed |= (1 << i);
        }

        key_list[i].first_state = key_list[i].second_state;
        key_list[i].second_state = pin_state;
    }
    pin_state_second = PORT_GetBit(key_list[5].port, key_list[5].pin);
    if (pin_state_second == RESET)
    {
        key_second_pressed = 1;
    }
    else
    {
        key_second_pressed = 0;
    }
}

void key_process(void)
{
    uint32_t i = 0;
    
    key_scan();

    for (i = 0; i < 5; i++)
    {
        if (keys_pressed & (1 << i))
        {
            if (key_second_pressed == 0)
            {
                if (key_list[i].func != NULL)
                {
                    key_list[i].func();
                }
            }
            else
            {
                if (key_list[i].func_second != NULL)
                {
                    key_list[i].func_second();
                }
            }

            keys_pressed = 0;
            break;
        }
    }
}

void BSP_KeyInit(void)
{
    uint8_t i;

    stc_port_init_t stcPortInit;
    MEM_ZERO_STRUCT(stcPortInit);
    stcPortInit.enExInt = Enable;
    stcPortInit.enPullUp = Enable;
    PORT_DebugPortSetting(TRST, Disable);

    for (i = 0; i < BSP_KEY_ROW_NUM; i++)
    {
        PORT_Init(BSP_KEYIN_PORT_PIN[i].port, BSP_KEYIN_PORT_PIN[i].pin, &stcPortInit);
    }
}

void dis_init(void)
{
    int i;
    uint32_t para;

    for (i = 0; i < tx_len; i++)
    {
        tx_buf[i] = i;
    }

    uint16_t crc16 = crc16_ccitt(tx_buf, tx_len - 2); /* 计算CRC校验值 */
    tx_buf[tx_len - 2] = (uint8_t)(crc16 >> 8);       /* CRC高字节 */
    tx_buf[tx_len - 1] = crc16 & 0xFF;                /* CRC低字节 */

    dis_set_cnt(0);
    dis_set_mode(0);

    para = RF_GetFreq();
    dis_set_fq((para / 100000));

    para = RF_GetCR();
    dis_set_cr(para);

    para = RF_GetSF();
    dis_set_sf(para);

    para = RF_GetBandWidth();
    dis_set_bw(para);

    dis_set_pl(tx_len);

    para = RF_GetTxPower();
    dis_set_txpower(para);

    oled_refresh();
}

void rf_rx_done_routine(void)
{
    rx_pkt_cnt++;
    dis_set_cnt(rx_pkt_cnt);
    oled_refresh();
}

void rf_tx_done_routine(void)
{
    tx_pkt_cnt++;
    dis_set_cnt(tx_pkt_cnt);
    oled_refresh();
    if ((tx_pkt_cnt < tx_pkt_max_num) && tx_ing)
    {
        SysTick_Delay(100);
        RF_TxSinglePkt(tx_buf, tx_len);
    }
    else
    {
        g_RFTxOta = false;  /* 标记单包数据发送完成 */
        tx_ing = 0;
    }
}

void rf_process(void)
{
    if(tx_carrywave_flag)
    {
        return;
    }
    
    if (CHECK_RF_IRQ()) /* 检测到RF中断，高电平表示有中断 */
    {
        uint8_t IRQFlag;
        IRQFlag = RF_GetIRQFlag();    /* 获取中断标志位 */
        if (IRQFlag & RF_IRQ_TX_DONE) /* 发送完成中断 */
        {
            RF_TurnoffPA();                /* 发送完成后须关闭PA */
            RF_ClrIRQFlag(RF_IRQ_TX_DONE); /* 清除发送完成中断标志位 */
            IRQFlag &= ~RF_IRQ_TX_DONE;
            RF_EnterStandbyState(); /* 发送完成后须设置为RF_STATE_STB3状态 */
            BSP_LedToggle();
            rf_tx_done_routine();
            printf("Tx Count:%d\r\n", tx_pkt_cnt); /* 打印发送次数 */
        }
        if (IRQFlag & RF_IRQ_RX_DONE) /* 接收完成中断 */
        {
            g_RfRxPkt.Snr = RF_GetPktSnr();                       /* 获取接收数据包的SNR值 */
            g_RfRxPkt.Rssi = RF_GetPktRssi();                     /* 获取接收数据包的RSSI值 */
            g_RfRxPkt.RxLen = RF_GetRecvPayload(g_RfRxPkt.RxBuf); /* 获取接收数据和长度 */

            if(key_set_test_mode1_flag != 1)  /* CHIPMODE_MODE0 */
            {
                printf(">>Received a packet!\r\n");
                printf("+RxLen=%d, Rx Count=%d\n", g_RfRxPkt.RxLen, ++g_RxCount);
                printf("+RxHexData:\r\n");
                print_hex(g_RfRxPkt.RxBuf, g_RfRxPkt.RxLen); /* 以十六进制方式打印接收数据 */
                printf("SNR:%ddB, RSSI:%ddBm \r\n", (int)g_RfRxPkt.Snr, (int)g_RfRxPkt.Rssi);
                
                BSP_LedToggle();
                rf_rx_done_routine();
            }
            else /* CHIPMODE_MODE1 */
            {
                g_RfRxPkt.RxLen = RF_GetRecvPayload(g_RfRxPkt.RxBuf);   /* 获取接收数据和长度 */
                uint8_t DateLen = g_RfRxPkt.RxLen - 2;                  /* 数据长度为接收长度减去CRC校验的2字节 */
                uint16_t crc16 = crc16_ccitt(g_RfRxPkt.RxBuf, DateLen); /* 计算CRC校验值 */
                
                printf("crc16=0x%04X\r\n", crc16); /* 打印CRC校验值 */
                /* 检查CRC校验 */
                if ((g_RfRxPkt.RxBuf[g_RfRxPkt.RxLen - 2] == (crc16 >> 8)) 
                     && (g_RfRxPkt.RxBuf[g_RfRxPkt.RxLen - 1] == (crc16 & 0xFF))) 
                {
                    printf(">>Received a packet!\r\n");
                    printf("+RxLen=%d, Rx Count=%d\n", g_RfRxPkt.RxLen, ++g_RxCount);
                    printf("+RxHexData:\r\n");
                    print_hex(g_RfRxPkt.RxBuf, g_RfRxPkt.RxLen); /* 以十六进制方式打印接收数据 */
                    printf("SNR:%ddB, RSSI:%ddBm \r\n", (int)g_RfRxPkt.Snr, (int)g_RfRxPkt.Rssi);
                    
                    BSP_LedToggle();
                    rf_rx_done_routine();
                }
                else
                {
                    printf("CRC error, RxLen=%d\r\n", g_RfRxPkt.RxLen);
                    printf("RxHexData:\r\n");
                    print_hex(g_RfRxPkt.RxBuf, g_RfRxPkt.RxLen); /* 以十六进制方式打印接收数据 */
                }
            }
            RF_ClrIRQFlag(RF_IRQ_RX_DONE); /* 清除接收完成中断标志位 */
            IRQFlag &= ~RF_IRQ_RX_DONE;
        }
        if (IRQFlag & RF_IRQ_CRC_ERR && (key_set_test_mode1_flag == 1)) /* CRC错误中断 */
        {
            RF_ClrIRQFlag(RF_IRQ_CRC_ERR); /* 清除CRC错误中断标志位 */
            IRQFlag &= ~RF_IRQ_CRC_ERR;
            printf(">>RF_IRQ_CRC_ERR\r\n");
        }
        if (IRQFlag & RF_IRQ_RX_TIMEOUT) /* 接收超时中断 */
        {
            RF_ClrIRQFlag(RF_IRQ_RX_TIMEOUT); /* 清除接收超时中断标志位 */
            IRQFlag &= ~RF_IRQ_RX_TIMEOUT;
            printf(">>RF_IRQ_RX_TIMEOUT\r\n");
        }

        if (IRQFlag)
        {
            RF_ClrIRQFlag(IRQFlag); /* 清除未处理的中断标志位 */
        }
    }
}

void KEY_Init(void)
{
    uint8_t i;

    stc_port_init_t stcPortInit;
    MEM_ZERO_STRUCT(stcPortInit);
    stcPortInit.enExInt = Enable;
    stcPortInit.enPullUp = Enable;
    PORT_DebugPortSetting(TRST,Disable);

    for (i = 0U; i < BSP_KEY_ROW_NUM; i++)
    {
        PORT_Init(BSP_KEYIN_PORT_PIN[i].port, BSP_KEYIN_PORT_PIN[i].pin, &stcPortInit);
    }
}
